Page({
  data: {
    messageList: [],
    unreadCount: 0,
    isLoading: true,
    // 消息类型统计
    messageStats: {
      leave: 0,
      attendance: 0,
      warning: 0
    },
    // 消息类型筛选
    currentType: 'all'
  },

  onLoad: function() {
    this.loadMessages();
  },

  onShow: function() {
    this.loadMessages();
  },

  onPullDownRefresh: function() {
    this.loadMessages().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载消息列表
  loadMessages: function() {
    this.setData({ isLoading: true });
    
    return new Promise((resolve) => {
      wx.request({
        url: 'http://localhost:3000/api/counselor/messages',
        method: 'GET',
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.statusCode === 200) {
            // 统计各类消息数量
            const stats = {
              leave: 0,
              attendance: 0,
              warning: 0
            };
            res.data.messages.forEach(msg => {
              if (stats[msg.type] !== undefined) {
                stats[msg.type]++;
              }
            });

            this.setData({
              messageList: res.data.messages || [],
              unreadCount: res.data.unreadCount || 0,
              messageStats: stats,
              isLoading: false
            });
          }
          resolve();
        },
        fail: () => {
          // 模拟数据
          const mockMessages = [
            {
              id: 1,
              type: 'leave',
              title: '请假审批提醒',
              content: '学生张三（2023001）申请请假2天，请及时审批',
              status: 'pending',
              createTime: '2023-12-18 10:30',
              isRead: false
            },
            {
              id: 2,
              type: 'attendance',
              title: '考勤异常提醒',
              content: '计算机科学1班有3名学生今日缺勤，请关注',
              createTime: '2023-12-18 09:15',
              isRead: false
            },
            {
              id: 3,
              type: 'warning',
              title: '学业预警通知',
              content: '李四（2023002）本学期有2门课程成绩不及格，需要特别关注',
              level: 'serious',
              createTime: '2023-12-17 16:45',
              isRead: true
            }
          ];

          const stats = {
            leave: 1,
            attendance: 1,
            warning: 1
          };

          this.setData({
            messageList: mockMessages,
            unreadCount: 2,
            messageStats: stats,
            isLoading: false
          });
          resolve();
        }
      });
    });
  },

  // 切换消息类型
  switchType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentType: type
    });
  },

  // 查看消息详情
  viewMessageDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type;
    
    // 根据消息类型跳转到不同页面
    let url = '';
    switch(type) {
      case 'leave':
        url = `/pages/counselor/qingjia/detail/detail?id=${id}`;
        break;
      case 'attendance':
        url = `/pages/counselor/kaoqin/detail/detail?id=${id}`;
        break;
      case 'warning':
        url = `/pages/counselor/warning/detail/detail?id=${id}`;
        break;
      default:
        url = `/pages/counselor/xiaoxi/detail/detail?id=${id}`;
    }
    
    wx.navigateTo({ url });
    this.markAsRead(id);
  },

  // 标记消息为已读
  markAsRead: function(id) {
    wx.request({
      url: `http://localhost:3000/api/counselor/messages/${id}/read`,
      method: 'PUT',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.updateMessageStatus(id);
        }
      }
    });
  },

  // 更新消息状态
  updateMessageStatus: function(id) {
    const messages = this.data.messageList;
    const index = messages.findIndex(item => item.id === id);
    
    if (index !== -1 && !messages[index].isRead) {
      messages[index].isRead = true;
      this.setData({
        messageList: messages,
        unreadCount: this.data.unreadCount - 1
      });
    }
  },

  // 全部标为已读
  markAllAsRead: function() {
    wx.showLoading({ title: '处理中' });
    
    wx.request({
      url: 'http://localhost:3000/api/counselor/messages/read-all',
      method: 'PUT',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const messages = this.data.messageList.map(msg => ({
            ...msg,
            isRead: true
          }));
          
          this.setData({
            messageList: messages,
            unreadCount: 0
          });
          
          wx.showToast({
            title: '已全部标为已读',
            icon: 'success'
          });
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  }
});